// const sheduler = (chunkTask) => {
//     setTimeout(() => {
//         // 当前时间
//         const now = performance.now()
//         chunkTask(() => performance.now() - now < 1)
//     }, 1000)
// }

import { ref } from 'vue'

export type Task = () => void
type Scheduler = (chunkTask: (goOn: () => boolean) => void) => void

const performTasks = (tasks: Task[], sheduler: Scheduler) => {
    if (tasks.length === 0) {
        return
    }

    let i = 0
    function _run() {
        sheduler((goOn) => {
            while (i < tasks.length && goOn()) {
                tasks[i++]()
            }
            if (i >= tasks.length) {
                return
            }
            _run()
        })
    }

    _run()
}

// 控制JS执行时机，解决一次性执行太多JS任务函数造成卡顿问题
export function idlePerformTasks(tasks: Task[]) {
    const scheduler: Scheduler = (chunkTask) => {
        requestIdleCallback((idel) => {
            chunkTask(() => idel.timeRemaining() > 0)
        })
    }

    performTasks(tasks, scheduler)
}

// 大量元素插入，优化加载白屏
export function useDefer() {
    const count = ref(0)

    function update() {
        count.value++
        requestAnimationFrame(update)
    }

    update()

    return function (n: number) {
        return count.value >= n
    }
}
